export class Chaos {
    private leadLetters: string = '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    private allLetters = this.leadLetters + '0123456789';

    private size = 0;
    private pool: string[] = [];
    private cache: Record<string, string> = {};

    public init(size: number, cache: Record<string, string>): void {
        this.size = size;
        this.cache = cache;
        for (let i = 0, len = this.leadLetters.length; i < len; i++) {
            this.pool.push(this.leadLetters[i]);
        }
        let start = 0, end = this.pool.length;
        while (this.pool.length < size) {
            for (let i = start; i < end; i++) {
                const s = this.pool[i];
                for (let j = 0, jlen = this.allLetters.length; j < jlen; j++) {
                    this.pool.push(s + this.allLetters[j]);
                }
            }
            start = end, end = this.pool.length;
        }
        const cacheValues = Object.values(cache);
        this.pool = this.pool.filter((v) => !cacheValues.includes(v));
    }

    public getChaos(s: string): string {
        let out = this.cache[s];
        if (out) {
            return out;
        }
        if (this.pool.length == 0) {
            // 扩大
            this.init(this.size * 2, this.cache);
        }
        out = this.pool.shift()!;
        this.cache[s] = out;
        return out;
    }
}
